<?php
class store_model extends MY_model
{
    public $id;
    public $product_id;
    public $table_id;
    public $quantity;

    public function get_elements()
    {
        $query = $this->db->query("SELECT * FROM store");
        return $this->to_domain_models($query->result());
    }

    public function get_element_by_id($id)
    {
        $query = $this->db->query("SELECT * FROM store WHERE id = ?",array($id));
        return $this->to_domain_model($query->row());
    }

    public function get_element_by_table_product($table_id,$product_id)
    {
        $query = $this->db->query("SELECT * FROM store WHERE table_id = ? AND product_id = ?",array($table_id,$product_id));
        return $this->to_domain_model($query->row());
    }

    public function get_elements_by_table($table_id)
    {
        $query = $this->db->query("SELECT * FROM store WHERE table_id = ?",array($table_id));
        return $this->to_domain_models($query->result());
    }

    public function get_element_by_table($table_id)
    {
        $query = $this->db->query("SELECT * FROM store WHERE table_id = ? LIMIT 1",array($table_id));
        return $this->to_domain_model($query->row());
    }

    public function add_product($data = array())
    {
        $this->db->insert('store',$data);
        if($this->db->affected_rows() > 0)
        {
            return true;
        }
        return false;
    }

    public function increase_quantity($id,$data)
    {
        $this->db->update('store',$data,array('id' => $id));
        if($this->db->affected_rows() > 0)
        {
            return true;
        }
        return false;
    }

    public function delete_by_table($table_id)
    {
        $this->db->delete('store',array('table_id' => $table_id));
        if($this->db->affected_rows() > 0)
        {
            return true;
        }
        return false;
    }

    // -------------------------------------------------------------------------------- PRIVATE PROPERTIES

    public function get_table_name()
    {
        return $this->table_model->get_element_by_id($this->table_id)->name;
    }

    public function get_sub_total()
    {
        return $this->products_model->get_element_by_id($this->product_id)->price * $this->quantity;
    }


    // -------------------------------------------------------------------------------- PRIVATE METHOD

    // Private method
    public function to_domain_model($item)
    {
        $model = new store_model();
        $model->id = isset($item->id) ? $item->id : '' ;
        $model->product_id = isset($item->product_id) ? $item->product_id : '' ;
        $model->table_id = isset($item->table_id) ? $item->table_id : '' ;
        $model->quantity = isset($item->quantity) ? $item->quantity : '0' ;
        return $model;
    }
}